package com.touchfired.server.handler;

import com.touchfired.common.core.event.impl.ConnectedEvent;
import com.touchfired.common.core.publisher.impl.EventPublisher;
import com.touchfired.common.spring.BeanLocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

/**
 * socket通道处理器
 *
 * @author 幸佳俊
 */
public class WebSocketChannelHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
//        dispatcher.doDispath(ctx, frame, SocketMessage.class);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            WebSocketServerProtocolHandler.HandshakeComplete hscEvt = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
            EventPublisher publisher = BeanLocator.getBean(EventPublisher.class);
            if (publisher != null) {
                publisher.publish(new ConnectedEvent(ctx, hscEvt.requestHeaders()));
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
